package com.after.saas.file.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.json.JSONUtil;
import com.after.saas.common.model.vo.FileVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description
 * @Classname CustomerFileUtil
 * @Author hjchen
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2023/4/20 17:27
 */

@Slf4j
@Component
public class CustomerFileUtil {

    private static String cacheDir = "D\\mnt\\cache\\";

    private static String realPath = "D\\mnt\\dev";

    private static String virtualPath = "/file";

    @Value("${upload.tomcat.cacheDir:D\\mnt\\cache\\}")
    public void setCacheDir(String cacheDir) {
        CustomerFileUtil.cacheDir = cacheDir;
    }

    @Value("${upload.realPath:D\\mnt\\dev}")
    public void setRealPath(String realPath) {
        CustomerFileUtil.realPath = realPath;
    }

    @Value("${upload.virtualPath:/file}")
    public void setVirtualPath(String virtualPath) {
        CustomerFileUtil.virtualPath = virtualPath;
    }

    /**
     * 复制文件并重命名
     *
     * @param fileList 附件列表
     * @return java.io.File[]
     * @author hjchen
     * @date 2023/4/19 14:39
     **/
    public static File[] copyAndRenameFile(List<FileVO> fileList) {
        log.info("cacheDir {} realPath {}  virtualPath {}", cacheDir, realPath, virtualPath);
        List<File> files = new ArrayList<>();
        for (FileVO enterpriseFile : fileList) {
            String fileName = cacheDir + enterpriseFile.getFileName();
            String src = getRealPath(enterpriseFile.getFilePath());
            log.info("src {} fileName {}", src, fileName);
            File file = new File(src);
            if (file.exists()) {
                files.add(FileUtil.copyFile(src, cacheDir + fileName, StandardCopyOption.REPLACE_EXISTING));
            }
        }
        return files.toArray(new File[0]);
    }

    /**
     * 复制文件并重命名
     *
     * @param fileList 附件列表
     * @return java.io.File[]
     * @author hjchen
     * @date 2023/4/19 14:39
     **/
    public static File[] creatDirAndRenameFile(List<FileVO> fileList) {
        log.info("cacheDir {} realPath {}  virtualPath {}", cacheDir, realPath, virtualPath);
        Map<String, List<FileVO>> fileMap = fileList.stream().collect(Collectors.groupingBy(FileVO::getCompanyName));
        File[] fileArr = new File[fileMap.size()];
        int i = 0;
        for (Map.Entry<String, List<FileVO>> entry : fileMap.entrySet()) {
            List<FileVO> files = entry.getValue();
            String dir = cacheDir + entry.getKey() + File.separator;
            for (FileVO enterpriseFile : files) {
                FileUtil.copyFile(getRealPath(enterpriseFile.getFilePath()), dir + enterpriseFile.getFileName(), StandardCopyOption.REPLACE_EXISTING);
            }
            fileArr[i] = new File(dir);
            i = ++i;
        }
        return fileArr;
    }

    /**
     * 获取文件真实路径
     *
     * @param filePath 文件地址
     * @return String
     * @author hjchen
     * @date 2023/4/19 14:39
     **/
    public static String getRealPath(String filePath) {
        String virtualPath = "D:/mnt";
        if (filePath.contains(virtualPath.substring(1))) {
            String tempPath = filePath.substring(virtualPath.length());
            if (tempPath.startsWith(File.separator) || tempPath.startsWith("/")) {
                filePath = realPath + tempPath;
            } else {
                filePath = realPath + File.separator + tempPath;
            }
        }
        return filePath;
    }

    /**
     * 获取文件真实路径
     *
     * @param files 删除文件
     * @author hjchen
     * @date 2023/4/19 14:39
     **/
    public static void del(File... files) {
        Arrays.stream(files).forEach(FileUtil::del);
    }

    public static void main(String[] args) {
        testZipDir(true);
    }

    public static void testZipDir(boolean withSrc) {
        String dir = "D:\\mnt\\";
        File[] files;
        if (withSrc) {
            files = creatDirAndRenameFile(getFileList());
        } else {
            files = copyAndRenameFile(getFileList());
        }
        String fileName = String.format("测试压缩并重命名文件-%s.zip", DateUtil.format(LocalDateTime.now(), DatePattern.NORM_DATE_PATTERN));
        File file = ZipUtil.zip(FileUtil.file(dir + fileName), withSrc, files);
        System.out.println(file.getAbsolutePath());
    }

    public static List<FileVO> getFileList() {
        String dir = "D:\\mnt\\";
        String suffix = ".pdf";
        List<FileVO> fileList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            if (i < 2) {
                FileVO yghEntMeansFile = new FileVO();
                yghEntMeansFile.setCompanyName("企业1");
                yghEntMeansFile.setFileName("测试" + i + suffix);
                yghEntMeansFile.setFilePath(dir + "test" + i + suffix);
                fileList.add(yghEntMeansFile);
            } else {
                FileVO yghEntMeansFile = new FileVO();
                yghEntMeansFile.setCompanyName("企业2");
                yghEntMeansFile.setFileName("测试" + i + suffix);
                yghEntMeansFile.setFilePath(dir + "test" + i + suffix);
                fileList.add(yghEntMeansFile);
            }
        }
        return fileList;
    }

    public static void testZip() {
        String dir = "D:\\mnt\\logs\\";
        String dir1 = "D:\\mnt\\logs\\企业1";
        String dir2 = "D:\\mnt\\logs\\企业2";
        File[] files = new File[2];
        files[0] = new File(dir1);
        files[1] = new File(dir2);
        String fileName = String.format("阳光化备案附件-%s.zip", DateUtil.format(LocalDateTime.now(), DatePattern.NORM_DATE_PATTERN));
        File file = ZipUtil.zip(FileUtil.file(dir + fileName), false, files);
        System.out.println(file.getAbsolutePath());
    }
}
